package com.etonenet.etpe.schedule;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.etonenet.etpe.entity.DailyCountApiLog;
import com.etonenet.etpe.repository.DailyCountApiLogRepository;
import com.etonenet.etpe.repository.PhoneApiLogRepository;
import com.etonenet.etpe.util.ApiStatus;

@Service
public class PhoneApiLogCountService {
  private Logger logger = LoggerFactory.getLogger(PhoneApiLogCountService.class);

  @Autowired
  private PhoneApiLogRepository phoneApiLogRepository;
  @Autowired
  private DailyCountApiLogRepository dailyCountApiLogRepository;

  /*
   * 每日数据统计
   */
  @Scheduled(cron = "0 30 0 * * *")
  public void dailyCount() {
    logger.info("apiLogDailyCount start");
    Date to = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
    Date from = DateUtils.addDays(to, -1);
    
    Map<String, DailyCountApiLog> map = getData(to, from);    
    for(String key:map.keySet()) {
      dailyCountApiLogRepository.save(map.get(key));
    }
    logger.info("apiLogDailyCount end");
  }

  private Map<String, DailyCountApiLog> getData(Date to, Date from) {
    Map<String, DailyCountApiLog> map = new HashMap<>();

    List<Object> list = phoneApiLogRepository.countBySpId(from, to);
    for (Object object : list) {
      Object[] cell = (Object[]) object;
      if (cell[0] != null) {
        DailyCountApiLog daily = new DailyCountApiLog();
        daily.setCountTime(from);
        daily.setSpId(cell[0].toString());
        daily.setTotalCount(Integer.parseInt(cell[1].toString()));
        map.put(daily.getSpId(), daily);
      }
    }

    List<Object> successList =
        phoneApiLogRepository.countBySpIdSuccess(from, to, ApiStatus.S_0.getCode());
    for (Object object : successList) {
      Object[] cell = (Object[]) object;
      if(cell[0] != null) {
        map.get(cell[0].toString()).setSuccessCount(Integer.parseInt(cell[1].toString()));
      }
    }
    return map;
  }
}
